package com.googlecode.sparda.commons.util;


/**
 * Class representing a simple chronometer.
 * @author Fabio Grucci (<i>alias</i> <b>Phoenix</b>)
 * @version 0.0.1
 * @since 0.0.1
 */
public class SimpleChronometer {
	/**
	 * The elapsed time in millis.
	 */
	private long elapsedTime;
	/**
	 * The starting time of current session.
	 */
	private long startingTime;
	/**
	 * <code>true</code> if running, <code>false</code> otherwise
	 */
	private boolean isRunning;
	
	/**
	 * Start the chronometer.
	 * If the {@link SimpleChronometer} is running the method return 
	 * a negative long equals to the delay of the start time.
	 * @return The elapsedTime in millis
	 */
	public long start() {
		if(this.isRunning)
			return this.startingTime - System.currentTimeMillis();
		this.isRunning = true;
		this.startingTime = System.currentTimeMillis();
		return this.elapsedTime;
	}

	/**
	 * Method that stop the Chronometer and return the last interval.
	 * @return the last interval
	 */
	public long stop() {
		if(!this.isRunning)
			return 0;
		final long stopTimeMillis = System.currentTimeMillis();
		final long interval = stopTimeMillis - this.startingTime;
		this.elapsedTime += interval;
		this.setRunning(false);
		return interval;
	}
	
	/**
	 * Method that return the elapsed time in millis.
	 * @return The elapsed time in millis
	 */
	public long getElapsedTime() {
		if(this.isRunning)
			return this.elapsedTime + System.currentTimeMillis() - this.startingTime;
		return this.elapsedTime;
	}
	/**
	 * Method that return <code>true</code> if the chronometer is running, <code>false</code> otherwise.
	 * @return <code>true</code> if running, <code>false</code> otherwise
	 */
	public boolean isRunning() {
		return this.isRunning;
	}
	
	private void setRunning(boolean isRunning) {
		this.isRunning = isRunning;
	}
	
}
